package com.lemon.core.mybatis.handler;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lemon.core.base.pojo.BaseEntity;
import com.lemon.core.base.context.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 字段自动填充
 *
 * @author pan
 * @link https://mp.baomidou.com/guide/auto-fill-metainfo.html
 * @since 2019-02-14
 */
@Component
public class LemonMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增填充创建时间
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) originalObject;
            entity.setCreateTime(now);
            entity.setCreateBy(UserContextHolder.getUsername());
            entity.setUpdateTime(now);
            entity.setUpdateBy(CharSequenceUtil.EMPTY);
        } else {
            if (metaObject.hasSetter(BaseEntity.CREATE_TIME_FIELD)) {
                this.strictInsertFill(metaObject, BaseEntity.CREATE_TIME_FIELD, () -> now, LocalDateTime.class);
            }
            if (metaObject.hasSetter(BaseEntity.CREATE_BY_FIELD)) {
                this.strictInsertFill(metaObject, BaseEntity.CREATE_BY_FIELD, UserContextHolder::getUsername, String.class);
            }
            if (metaObject.hasSetter(BaseEntity.UPDATE_TIME_FIELD)) {
                this.strictInsertFill(metaObject, BaseEntity.UPDATE_TIME_FIELD, () -> now, LocalDateTime.class);
            }
            if (metaObject.hasSetter(BaseEntity.UPDATE_BY_FIELD)) {
                this.strictInsertFill(metaObject, BaseEntity.UPDATE_BY_FIELD, () -> CharSequenceUtil.EMPTY, String.class);
            }
        }
    }

    /**
     * 更新填充更新时间
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) originalObject;
            entity.setUpdateTime(now);
            entity.setUpdateBy(UserContextHolder.getUsername());
        } else {
            if (metaObject.hasSetter(BaseEntity.UPDATE_TIME_FIELD)) {
                this.strictUpdateFill(metaObject, BaseEntity.UPDATE_TIME_FIELD, () -> now, LocalDateTime.class);
            }
            if (metaObject.hasSetter(BaseEntity.UPDATE_BY_FIELD)) {
                this.strictUpdateFill(metaObject, BaseEntity.UPDATE_BY_FIELD, UserContextHolder::getUsername, String.class);
            }
        }
    }

}
